package com.leetroll.app.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.leetroll.api.service.ItemService;
import com.leetroll.api.service.SysConfigService;
import com.leetroll.api.service.TagService;
import com.leetroll.app.service.CatMenuService;
import com.leetroll.common.entity.SysConfig;
import com.leetroll.common.entity.Tag;
import com.leetroll.common.enums.EConfigKey;
import com.leetroll.common.utils.JsonUtils;
import com.leetroll.common.vo.CatMenuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.leetroll.common.enums.ECat.fromName;

@Service
@Slf4j
public class CatMenuServiceImpl implements CatMenuService {

    private final SysConfigService sysConfigService;
    private final ItemService itemService;
    private final TagService tagService;

    @Autowired
    public CatMenuServiceImpl(SysConfigService sysConfigService, ItemService itemService, TagService tagService) {
        this.sysConfigService = sysConfigService;
        this.itemService = itemService;
        this.tagService = tagService;
    }

    @Override
//    @Cacheable(cacheNames = "allCatMenus")
    public List<CatMenuVO> all() {
        List<CatMenuVO> result = new ArrayList<>();
        SysConfig sysConfig = sysConfigService.getByKey(EConfigKey.CAT_MENU.getKey());
        if (sysConfig == null) return result;

        String json = sysConfig.getValue();
        JsonArray object = JsonUtils.strToJsonArray(json);
        for (JsonElement element : object) {
            CatMenuVO menuVO = (CatMenuVO) JsonUtils.jsonToObject(element.toString(), CatMenuVO.class);
            Integer catId = fromName(menuVO.getLink()).getCatId();
            Integer size = itemService.totalSize(catId, "all");
            menuVO.setCnt(size);
            for (CatMenuVO subMenu1 : menuVO.getSub()) {
                for (CatMenuVO subMenu2 : subMenu1.getSub()) {
                    Integer sizeMenu2 = itemService.totalSize(catId, subMenu1.getLink() + "-" + subMenu2.getLink());
                    subMenu2.setCnt(sizeMenu2);
                    for (CatMenuVO subMenu3 : subMenu2.getSub()) {
                        Tag tag = tagService.getByWord(subMenu3.getLink());
                        Integer sizeMenu3 = 0;
                        if (tag == null) {
                            sizeMenu3 = itemService.totalSize(catId, subMenu1.getLink() + "-" + subMenu3.getLink());
                        } else {
                            sizeMenu3 = itemService.totalSize(catId, subMenu1.getLink() + "-" + tag.getTag());
                        }
                        subMenu3.setCnt(sizeMenu3);
                    }
                }
            }
            result.add(menuVO);
        }
        return result;
    }
}